#!/bin/bash

# 红队后门状态检查脚本
# 快速检查所有后门的状态

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印横幅
print_banner() {
    echo -e "${BLUE}"
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║                    privilegeMaintenance v1.0                ║"
    echo "║                     后门状态检查工具                         ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
}

# 检查SSH后门
check_ssh_backdoor() {
    echo -e "${BLUE}[*] 检查SSH后门...${NC}"
    
    # 检查SSH密钥后门
    if [ -f ~/.ssh/authorized_keys ]; then
        key_count=$(wc -l < ~/.ssh/authorized_keys)
        echo -e "${GREEN}  ✅ SSH密钥文件存在 (${key_count} 个密钥)${NC}"
        
        # 检查可疑密钥
        if grep -q "# redteam" ~/.ssh/authorized_keys 2>/dev/null; then
            echo -e "${YELLOW}  ⚠️ 发现红队标记密钥${NC}"
        fi
    else
        echo -e "${RED}  ❌ SSH密钥文件不存在${NC}"
    fi
    
    # 检查SSH配置
    if [ -f /etc/ssh/sshd_config ]; then
        if grep -q "PermitRootLogin yes" /etc/ssh/sshd_config; then
            echo -e "${GREEN}  ✅ SSH root登录已启用${NC}"
        fi
        
        if grep -q "PasswordAuthentication yes" /etc/ssh/sshd_config; then
            echo -e "${GREEN}  ✅ SSH密码认证已启用${NC}"
        fi
    fi
    
    # 检查SSH服务状态
    if systemctl is-active --quiet ssh || systemctl is-active --quiet sshd; then
        echo -e "${GREEN}  ✅ SSH服务运行中${NC}"
    else
        echo -e "${RED}  ❌ SSH服务未运行${NC}"
    fi
}

# 检查Crontab后门
check_crontab_backdoor() {
    echo -e "${BLUE}[*] 检查Crontab后门...${NC}"
    
    # 检查用户crontab
    if crontab -l 2>/dev/null | grep -v "^#" | grep -q "."; then
        cron_count=$(crontab -l 2>/dev/null | grep -v "^#" | grep -c ".")
        echo -e "${GREEN}  ✅ 用户Crontab存在 (${cron_count} 个任务)${NC}"
        
        # 检查可疑任务
        if crontab -l 2>/dev/null | grep -q "bash\|sh\|python\|perl"; then
            echo -e "${YELLOW}  ⚠️ 发现脚本执行任务${NC}"
        fi
    else
        echo -e "${RED}  ❌ 用户Crontab为空${NC}"
    fi
    
    # 检查系统crontab
    if [ -d /etc/cron.d ]; then
        cron_files=$(find /etc/cron.d -name "*" -type f | wc -l)
        if [ $cron_files -gt 0 ]; then
            echo -e "${GREEN}  ✅ 系统Cron目录存在 (${cron_files} 个文件)${NC}"
        fi
    fi
    
    # 检查crond服务
    if systemctl is-active --quiet cron || systemctl is-active --quiet crond; then
        echo -e "${GREEN}  ✅ Cron服务运行中${NC}"
    else
        echo -e "${RED}  ❌ Cron服务未运行${NC}"
    fi
}

# 检查服务后门
check_service_backdoor() {
    echo -e "${BLUE}[*] 检查服务后门...${NC}"
    
    # 检查systemd服务
    if [ -d /etc/systemd/system ]; then
        # 查找可疑服务
        suspicious_services=$(find /etc/systemd/system -name "*.service" -exec grep -l "bash\|sh\|python" {} \; 2>/dev/null | wc -l)
        if [ $suspicious_services -gt 0 ]; then
            echo -e "${YELLOW}  ⚠️ 发现 ${suspicious_services} 个可疑systemd服务${NC}"
        fi
    fi
    
    # 检查运行中的服务
    active_services=$(systemctl list-units --type=service --state=active | grep -c "active")
    echo -e "${GREEN}  ✅ 活跃服务数量: ${active_services}${NC}"
    
    # 检查特定后门服务
    backdoor_services=("redteam-agent" "system-monitor" "log-cleaner")
    for service in "${backdoor_services[@]}"; do
        if systemctl is-active --quiet "$service"; then
            echo -e "${GREEN}  ✅ 后门服务 ${service} 运行中${NC}"
        fi
    done
}

# 检查进程后门
check_process_backdoor() {
    echo -e "${BLUE}[*] 检查进程后门...${NC}"
    
    # 检查可疑进程
    suspicious_processes=$(ps aux | grep -E "(bash|sh|python|perl)" | grep -v grep | wc -l)
    echo -e "${GREEN}  ✅ 脚本进程数量: ${suspicious_processes}${NC}"
    
    # 检查隐藏进程
    if command -v unhide >/dev/null 2>&1; then
        echo -e "${BLUE}  [*] 运行unhide检查隐藏进程...${NC}"
        hidden_count=$(unhide proc 2>/dev/null | grep -c "Found HIDDEN")
        if [ $hidden_count -gt 0 ]; then
            echo -e "${YELLOW}  ⚠️ 发现 ${hidden_count} 个隐藏进程${NC}"
        else
            echo -e "${GREEN}  ✅ 未发现隐藏进程${NC}"
        fi
    fi
    
    # 检查网络连接
    network_connections=$(netstat -tulpn 2>/dev/null | grep LISTEN | wc -l)
    echo -e "${GREEN}  ✅ 监听端口数量: ${network_connections}${NC}"
}

# 检查文件后门
check_file_backdoor() {
    echo -e "${BLUE}[*] 检查文件后门...${NC}"
    
    # 检查bashrc后门
    bashrc_files=("~/.bashrc" "~/.bash_profile" "/etc/bash.bashrc" "/etc/profile")
    for file in "${bashrc_files[@]}"; do
        expanded_file=$(eval echo "$file")
        if [ -f "$expanded_file" ]; then
            if grep -q "alias\|function\|export" "$expanded_file"; then
                echo -e "${GREEN}  ✅ ${file} 存在配置${NC}"
            fi
        fi
    done
    
    # 检查SUID文件
    suid_count=$(find /usr/bin /bin /usr/sbin /sbin -perm -4000 2>/dev/null | wc -l)
    echo -e "${GREEN}  ✅ SUID文件数量: ${suid_count}${NC}"
    
    # 检查可疑文件
    suspicious_locations=("/tmp" "/var/tmp" "/dev/shm")
    for location in "${suspicious_locations[@]}"; do
        if [ -d "$location" ]; then
            file_count=$(find "$location" -type f 2>/dev/null | wc -l)
            if [ $file_count -gt 0 ]; then
                echo -e "${YELLOW}  ⚠️ ${location} 中有 ${file_count} 个文件${NC}"
            fi
        fi
    done
}

# 检查网络后门
check_network_backdoor() {
    echo -e "${BLUE}[*] 检查网络后门...${NC}"
    
    # 检查监听端口
    if command -v netstat >/dev/null 2>&1; then
        listening_ports=$(netstat -tulpn 2>/dev/null | grep LISTEN | awk '{print $4}' | cut -d: -f2 | sort -n | uniq)
        echo -e "${GREEN}  ✅ 监听端口:${NC}"
        for port in $listening_ports; do
            echo -e "${GREEN}    - $port${NC}"
        done
    fi
    
    # 检查iptables规则
    if command -v iptables >/dev/null 2>&1; then
        rule_count=$(iptables -L 2>/dev/null | grep -c "^ACCEPT\|^DROP\|^REJECT")
        echo -e "${GREEN}  ✅ iptables规则数量: ${rule_count}${NC}"
    fi
    
    # 检查网络配置
    if [ -f /etc/hosts ]; then
        hosts_entries=$(grep -v "^#\|^$" /etc/hosts | wc -l)
        echo -e "${GREEN}  ✅ hosts文件条目: ${hosts_entries}${NC}"
    fi
}

# 检查日志痕迹
check_log_traces() {
    echo -e "${BLUE}[*] 检查日志痕迹...${NC}"
    
    # 检查认证日志
    auth_logs=("/var/log/auth.log" "/var/log/secure")
    for log in "${auth_logs[@]}"; do
        if [ -f "$log" ]; then
            recent_logins=$(tail -100 "$log" 2>/dev/null | grep -c "Accepted\|session opened")
            echo -e "${GREEN}  ✅ ${log} 最近登录: ${recent_logins}${NC}"
        fi
    done
    
    # 检查命令历史
    if [ -f ~/.bash_history ]; then
        history_size=$(wc -l < ~/.bash_history)
        echo -e "${GREEN}  ✅ Bash历史记录: ${history_size} 条${NC}"
    fi
    
    # 检查系统日志
    if [ -f /var/log/syslog ]; then
        recent_errors=$(tail -100 /var/log/syslog 2>/dev/null | grep -c "ERROR\|WARN")
        echo -e "${GREEN}  ✅ 系统日志错误: ${recent_errors}${NC}"
    fi
}

# 生成状态报告
generate_report() {
    echo -e "${BLUE}[*] 生成状态报告...${NC}"
    
    report_file="/tmp/backdoor_status_$(date +%Y%m%d_%H%M%S).txt"
    
    {
        echo "=== 红队后门状态报告 ==="
        echo "生成时间: $(date)"
        echo "主机名: $(hostname)"
        echo "用户: $(whoami)"
        echo "系统: $(uname -a)"
        echo ""
        
        echo "=== 系统信息 ==="
        echo "运行时间: $(uptime)"
        echo "内存使用: $(free -h | grep Mem)"
        echo "磁盘使用: $(df -h / | tail -1)"
        echo ""
        
        echo "=== 网络状态 ==="
        echo "网络接口:"
        ip addr show 2>/dev/null || ifconfig 2>/dev/null
        echo ""
        
        echo "=== 进程状态 ==="
        echo "运行进程数: $(ps aux | wc -l)"
        echo "CPU使用率前5:"
        ps aux --sort=-%cpu | head -6
        echo ""
        
        echo "=== 安全检查 ==="
        echo "SELinux状态: $(getenforce 2>/dev/null || echo "未安装")"
        echo "AppArmor状态: $(aa-status 2>/dev/null | head -1 || echo "未安装")"
        echo "防火墙状态: $(ufw status 2>/dev/null || iptables -L | head -1 2>/dev/null || echo "未知")"
        
    } > "$report_file"
    
    echo -e "${GREEN}  ✅ 报告已保存到: ${report_file}${NC}"
}

# 主函数
main() {
    print_banner
    
    echo -e "${BLUE}开始检查后门状态...${NC}"
    echo ""
    
    check_ssh_backdoor
    echo ""
    
    check_crontab_backdoor
    echo ""
    
    check_service_backdoor
    echo ""
    
    check_process_backdoor
    echo ""
    
    check_file_backdoor
    echo ""
    
    check_network_backdoor
    echo ""
    
    check_log_traces
    echo ""
    
    # 如果指定了报告参数
    if [ "$1" = "--report" ] || [ "$1" = "-r" ]; then
        generate_report
        echo ""
    fi
    
    echo -e "${GREEN}✅ 状态检查完成${NC}"
    echo ""
    echo -e "${YELLOW}💡 提示:${NC}"
    echo -e "${YELLOW}  - 使用 --report 参数生成详细报告${NC}"
    echo -e "${YELLOW}  - 使用 python redteam_launcher.py --interactive 进入交互模式${NC}"
    echo -e "${YELLOW}  - 使用 python redteam_launcher.py --evacuate fast 快速撤离${NC}"
}

# 检查参数
if [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  --help, -h     显示帮助信息"
    echo "  --report, -r   生成详细状态报告"
    echo ""
    echo "示例:"
    echo "  $0              # 基本状态检查"
    echo "  $0 --report     # 生成详细报告"
    exit 0
fi

# 运行主函数
main "$@"